import { OneModal } from '@/components/one-ui';
import { ContractManageAPI } from '../common/type';
import { IOneModalRef } from '@/pages/type';
import { Ref, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { UpdateTableCommon } from './UpdateTableCommon';
import { ConractControllerContext, IContractsActionEnum } from '../common';
import { materialTableService } from '../services';
import { materialTableConfig } from '../mconfig';
import { Button, Col, Row, message } from 'antd';
import { getColorTextLoadMap, getKeyRouter, onCloseModalCommon } from '@/utils';
import { OpenMaterialType } from './OpenMaterialType';
import { showTotalInfo } from '@/common/constVariable';
import { UpdateNeedMaterialAddModal } from './OpenAddMetailModal';

export const OpenMaterialModal: React.FC<ContractManageAPI.IOpenMaterialModal> = ({ onClose, isShowModal }) => {
  /**弹框的ref*/
  const updateModalRef: Ref<IOneModalRef> = useRef(null);

  /** 获取上下文 */
  const { curRes, styleFixCls, contractDispatch, contarctJsonList, contractDetailInfo, contractForm } = useContext(ConractControllerContext);

  /** 获取列表 */
  const { data, params, loading, pagination, searchList, loadMdicMapObj, getManageData } = materialTableService(curRes);

  const dataRowMemo = useMemo(() => {
    let dataRow: Record<string, any>[] = [];

    if (data?.rows?.length > 0) {
      data?.rows?.forEach((item: any) => {
        const formDetail: Record<string, any>[] = contractForm.getFieldValue('detailList')?.length > 0 ? contractForm.getFieldValue('detailList') : [];
        const itemInfo: Record<string, any> | any = formDetail?.find((itemForm: any) => itemForm?.materialID == item?.id);
        let info: Record<string, any> = {};
        if (itemInfo && JSON.stringify(itemInfo) != '{}') {
          info = {
            ...item,
            ...itemInfo,
            materialID: item?.id,
          };
        } else {
          info = {
            ...item,
            materialID: item?.id,
          };
        }
        delete info['id'];
        dataRow?.push(info);
      });
    }
    return dataRow;
  }, [data, contractForm.getFieldValue('detailList')]);

  /** 暂时保存选中的值 */
  const [checkMaterialList, setCheckMaterialList] = useState<Record<string, any>[]>([]);

  /** 选中树的key */
  const [selectKeys, setSelectKeys] = useState<React.Key[]>([]);

  /** 是否显示添加物料弹窗 */
  const [addMModal, setAddMModal] = useState<Record<string, any> | null>();

  /** 搜索 */
  const onSearch = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 重置 */
  const onReset = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 分页change 方法 */
  const onPageChange = (current: number, pageSize: number) => {
    getManageData({ ...params, current, pageSize });
  };

  /** 点击选中 */
  const onSelectTable = (selectInfo: any) => {
    setCheckMaterialList(selectInfo);
  };

  /** 初始化 */
  useEffect(() => {
    if (isShowModal) {
      const formDetailList: object[] = contractForm.getFieldValue('detailList');
      // const newFormList: object[] = formDetailList?.filter((item: any) => item?.materialID)
      setCheckMaterialList(formDetailList);
      // contractDispatch({
      //   type: IContractsActionEnum.CONTRACT_JSONLIST,
      //   payload: {
      //     ...contarctJsonList,
      //     detailList: formDetailList,
      //   },
      // });
    }
  }, [isShowModal]);

  useEffect(() => {
    getManageData({ state: '2' });
  }, []);

  /** 点击选中 */
  const onSave = () => {
    if (checkMaterialList && checkMaterialList?.length > 0) {
      const materList: Record<string, any>[] = [];

      let addModifyList: Record<string, any>[] = [];

      checkMaterialList?.forEach((item: any) => {
        let itemObj: Record<string, any> = {
          // ...item,
          // key: item?.materialID,
          id: item?.id,
          key: `detailList-${getKeyRouter()}`,
          materialID: item?.materialID,
          materialName: item?.materialName ? item?.materialName : item?.fullName,
          materialNum: item?.materialNum,
          specInfo: item?.specInfo ? item?.specInfo : item?.modelNum,
          priceInTax: item?.priceInTax ? item?.priceInTax : item?.unitPrice ? item?.unitPrice : 0,
          deliveryTime: item?.deliveryTime ? item?.deliveryTime : null,
          deliveryAddress: item?.deliveryAddress ? item?.deliveryAddress : null,
          deliveryStyle: item?.deliveryStyle ? item?.deliveryStyle : null,
          taxRate: item?.taxRate ? item?.taxRate : contractForm?.getFieldValue('taxRate'),
          unitBusiness: item?.unitBusiness ? item?.unitBusiness : null,
          unitBusinessName: item?.unitBusinessName ? getColorTextLoadMap(item?.unitBusinessName)?.colorText : null,
          expectNum: item?.expectNum ? item?.expectNum : 0,
          sumInTax: item?.sumInTax ? item?.sumInTax : 0,
          versionNum: 0,
          modifyFlag: item?.modifyFlag,
          brandType: item?.brandType ? item?.brandType : null,
          supplyType: item?.supplyType ? item?.supplyType : null,
          // createrID: getUserID(),
          // createPositionID: getPosIDs(),
          // createDepartmentID: getUserDepID(),
          // createCompanyID: getCompanyID(),
        };

        materList?.push(itemObj);
      });

      let detailList: Record<string, any>[] = contractForm.getFieldValue('detailList')?.length > 0 ? contractForm.getFieldValue('detailList') : [];
      let addList: Record<string, any>[] = [];
      let delList: Record<string, any>[] = [];

      if (detailList && detailList?.length > 0) {
        materList?.forEach((itemBrie: any) => {
          const addInfo = detailList?.find((itemInfo: any) => itemInfo?.materialID == itemBrie?.materialID);
          if (addInfo && addInfo?.id && itemBrie?.id && (addInfo?.modifyFlag != null || addInfo?.modifyFlag != undefined)) {
            addList?.push({
              ...itemBrie,
              modifyFlag: '1',
            });
          } else if (!(addInfo && addInfo?.id) || !itemBrie?.id) {
            delete itemBrie['id'];
            addList?.push({
              ...itemBrie,
              modifyFlag: '0',
            });
          }
        });
        detailList?.forEach((itemInfo: any) => {
          if (itemInfo?.materialID && itemInfo?.id) {
            const delInfo = materList?.filter((itemBrie: any) => itemInfo?.materialID == itemBrie?.materialID);
            if (!(delInfo && delInfo?.length > 0)) {
              delList?.push({
                ...itemInfo,
                modifyFlag: '2',
              });
            }
          }
        });
      } else {
        materList?.forEach((item: any) => {
          addList?.push({
            ...item,
            modifyFlag: '0',
          });

          addModifyList?.push({
            ...item,
            modifyFlag: '0',
          });
        });
      }

      let arr = [...addList, ...delList];
      let commonList: any = [];

      (contarctJsonList['detailList'] || []).map((item) => {
        let isHaveList = arr.filter((e) => item.materialID == e.materialID);
        if (!isHaveList?.length) commonList.push(item);
      });

      (arr || []).forEach((item) => {
        let obj = (contarctJsonList['detailList'] || []).filter((e) => item.materialID == e.materialID);
        if (obj && obj.length) item = obj[0];
      });

      contractDispatch({
        type: IContractsActionEnum.CONTRACT_JSONLIST,
        payload: {
          ...contarctJsonList,
          detailList: [...arr, ...commonList],
        },
      });

      contractForm.setFieldsValue({
        detailList: materList,
      });

      onCloseModalCommon(updateModalRef);
    } else {
      message.error('请至少选择一个物料');
    }
  };

  /**左侧数据点击事件过滤数据*/
  const onSelectLeftTree = (val: string | null) => {
    if (val) {
      getManageData({ materialType: val });
    } else {
      getManageData({ materialType: null });
    }
  };

  /**弹窗按钮*/
  const footerRender = () => {
    return (
      <>
        <Button onClick={() => onCloseModalCommon(updateModalRef)}>取消</Button>
        {curRes?.['/contractController/addMaterial'] && (
          <Button type={'primary'} onClick={() => setAddMModal({ isShow: true })}>
            添加
          </Button>
        )}
        <Button type={'primary'} onClick={onSave}>
          确认
        </Button>
      </>
    );
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={updateModalRef}
        title={'物料列表'}
        onCancel={onClose}
        width={document.body.clientWidth * 0.68}
        bodyStyle={{ height: document.body.clientHeight * 0.6, padding: 10 }}
        footer={footerRender()}
      >
        <Row className={`${styleFixCls}materialModal`}>
          <Col span={6}>
            <OpenMaterialType onSelect={onSelectLeftTree} onTreeKey={{ selectKeys, setSelectKeys }} loadMdicMapObj={loadMdicMapObj} />
          </Col>
          <Col span={18}>
            <UpdateTableCommon
              styleFixCls={styleFixCls}
              searchProps={{
                searchList,
                onReset,
                onSearch,
              }}
              selectTablePorps={{
                onSelectTable,
                selectRowObjList: checkMaterialList,
                selectType: 'checkbox',
                setCheckRows: setCheckMaterialList,
                getCheckboxProps: (record: Record<string, any>) => ({
                  disabled: record?.state != 2,
                }),
              }}
              tableProps={{
                columns: materialTableConfig(),
                loading,
                dataSource: dataRowMemo,
                pagination,
                onPageChange,
                rowKey: 'materialID',
                tableTotalShow: (total: any, range: any) => {
                  return (
                    <div style={{ display: 'flex', width: '100%', justifyContent: 'space-between' }}>
                      <div>
                        已选择<strong style={{ color: 'red' }}> {checkMaterialList?.length} </strong>条物料
                      </div>
                      <div>{showTotalInfo(total, range)}</div>
                    </div>
                  );
                },
              }}
            />
          </Col>
        </Row>
      </OneModal>

      {addMModal?.isShow && (
        <UpdateNeedMaterialAddModal prefixCls={''} onClose={() => setAddMModal(null)} onOk={() => getManageData({ current: 1, pageSize: 10 })} />
      )}
    </>
  );
};
